<template>
  <!-- 做为选择商品的sku列表 -->
  <el-table
    ref="activitySkuListRef"
    :data="formData!.skus!"
    max-height="500"
    size="small"
    :row-key="getRowKey"
    @select-all="handleSelectAll"
    @select="handleSelect"
  >
    <el-table-column v-if="isComponent" type="selection" reserve-selection width="45" />
    <el-table-column align="center" label="ID">
      <template #default="{ row }"> {{ row.skuId }} {{ row.isSelect }} </template>
    </el-table-column>

    <el-table-column align="left" label="商品信息" min-width="300">
      <template #default="{ row }">
        <div class="flex items-center">
          <div>
            <el-image
              :preview-teleported="true"
              :src="row.picUrl"
              class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
            />
          </div>
          <div class="flex items-center">
            <meton-tag
              v-if="row?.spuType == 2"
              :dict-type="DICT_TYPE.PRODUCT_SPU_TYPE2"
              :value="row?.skuType"
              effect="plain"
            />
            <meton-tag
              v-else-if="row?.spuType == 4"
              :dict-type="DICT_TYPE.PRODUCT_SPU_TYPE4"
              :value="row?.skuType"
              effect="plain"
            />
            <meton-tag
              :dict-type="DICT_TYPE.PRODUCT_SPU_TYPE"
              :value="row?.spuType"
              effect="plain"
              v-else
            />

            <el-text truncated> {{ row.spuName }} </el-text>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column align="center" label="规格" min-width="120">
      <template #default="{ row }">
        {{ row.specContent }}
      </template>
    </el-table-column>
    <el-table-column align="center" label="零售价(元)" min-width="80">
      <template #default="{ row }">
        {{ row.price }}
      </template>
    </el-table-column>

    <el-table-column align="center" label="理论可用次数" min-width="80" v-if="!hideUsableTimes">
      <template #default="{ row }">
        {{ row.usableTimes }}
      </template>
    </el-table-column>
    <el-table-column align="center" v-if="isDetail" label="最低价(元)" min-width="80">
      <template #default="{ row }">
        {{ row.lowPrice }}
      </template>
    </el-table-column>
    <!-- <el-table-column align="center" label="销量" v-if="isDetail" min-width="80">
      <template #default="{ row }">
        {{ row.salesCount }}
      </template>
    </el-table-column> -->
    <el-table-column align="center" label="库存" min-width="80" v-if="!hideStock">
      <template #default="{ row }">
        {{ row.stock }}
      </template>
    </el-table-column>

    <el-table-column align="center" label="销售渠道" v-if="isDetail" min-width="100">
      <template #default="{ row }">
        {{ row.salesChannel }}
      </template>
    </el-table-column>
    <el-table-column align="center" label="来源" v-if="isDetail" min-width="100">
      <template #default="{ row }">
        {{ row.sourceTypeName }}
      </template>
    </el-table-column>
    <el-table-column align="center" label="状态" v-if="isDetail" min-width="80">
      <template #default="{ row }">
        {{ row.status }}
      </template>
    </el-table-column>

    <!--  方便扩展每个配置的属性不一样  -->
    <slot name="extension"></slot>
    <el-table-column v-if="!isDetail" align="center" label="操作" min-width="90">
      <template #default="{ row }">
        <el-button type="primary" link @click="deleteSku(row.skuId)"> 删除 </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts" setup>
import { PropType, Ref } from 'vue'
import { propTypes } from '@/utils/propTypes'
import type { Sku, Spu } from '@/api/mall/product/spu'
import { RuleConfig } from '@/views/mall/product/spu/components/index'
import { ElTable } from 'element-plus'
import { DICT_TYPE } from '@/utils/dict'

defineOptions({ name: 'SkuList' })

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },

  ruleConfig: {
    type: Array as PropType<RuleConfig[]>,
    default: () => []
  },
  isBatch: propTypes.bool.def(false), // 是否作为批量操作组件
  isDetail: propTypes.bool.def(false), // 是否作为 sku 详情组件
  isComponent: propTypes.bool.def(false), // 是否作为 sku 选择组件
  isActivityComponent: propTypes.bool.def(false), // 是否作为 sku 活动配置组件
  hideStock: propTypes.bool.def(false), //是否隐藏库存
  hideUsableTimes: propTypes.bool.def(true)
})
const formData: Ref<Spu | undefined> = ref<Spu>() // 表单数据

const emit = defineEmits(['selectionChange', 'selectRow', 'delete'])
/**
 * 选择时触发
 * @param Sku 传递过来的选中的 sku 是一个数组
 */
const isAllSelect = ref<any>([])
const handleSelectAll = (val: Sku[]) => {
  if (val.length > 0) {
    isAllSelect.value = val
    val.forEach((ele) => {
      handleSelect(val, ele)
    })
  } else {
    isAllSelect.value.forEach((ele) => {
      handleSelect([], ele)
    })
  }
  // emit('selectionChange', val)
}
const handleSelect = (val: Sku[], row: Sku) => {
  let type = 'add'
  let selectedSkuIds = [] as any
  if (val.length === 0) {
    selectedSkuIds = []
  } else {
    selectedSkuIds = val.map((sku) => sku.skuId!)
  }
  if (selectedSkuIds.includes(row.skuId)) {
    type = 'add'
  } else {
    type = 'delete'
  }
  let params = {
    type: type,
    skuId: row.skuId
  }
  emit('selectRow', params)
}

/**
 * 将传进来的值赋值给 skuList
 */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) return
    formData.value = data
  },
  {
    deep: true,
    immediate: true
  }
)
const getRowKey = (row) => {
  return row.skuId
}

const activitySkuListRef = ref<InstanceType<typeof ElTable>>()

const getSkuTableRef = () => {
  return activitySkuListRef.value
}
const message = useMessage() // 消息弹窗

const deleteSku = async (skuId: number) => {
  await message.confirm('是否删除商品编号为' + skuId + '的数据？')
  const index = formData.value!.skus!.findIndex((item) => item.skuId == skuId)
  formData.value!.skus!.splice(index, 1)
  emit('delete', skuId)
}

/**
 * 保存时，每个商品规格的表单要校验下。例如说，销售金额最低是 0.01 这种。
 */
const validateSku = () => {
  let warningInfo = '请检查商品各行相关属性配置，'
  let validate = true // 默认通过
  for (const sku of formData.value!.skus!) {
    // 作为活动组件的校验
    for (const rule of props?.ruleConfig) {
      const arg = getValue(sku, rule.name)
      if (!rule.rule(arg)) {
        validate = false // 只要有一个不通过则直接不通过
        warningInfo += rule.message
        break
      }
    }
    // 只要有一个不通过则结束后续的校验
    if (!validate) {
      message.warning(warningInfo)
      throw warningInfo
    }
  }
}
const getValue = (obj, arg) => {
  const keys = arg.split('.')
  let value = obj
  for (const key of keys) {
    if (value && typeof value === 'object' && key in value) {
      value = value[key]
    } else {
      value = undefined
      break
    }
  }
  return value
}
// 暴露出生成 sku 方法，给添加属性成功时调用
defineExpose({ getSkuTableRef, validateSku })
</script>
